<?php


namespace app\admin\model;


use app\admin\model\UserList as user;
use app\common\service\ReplyService;
use app\sys\service\GateCli;
use GatewayWorker\Lib\Gateway;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\facade\Cache;
use think\facade\Log;
use think\Model;

class Reply extends Model
{
    protected $autoWriteTimestamp = true;

    /**
     * @param $name
     * @return string
     */
    public static function add($name, $dutyId, $no): string
    {
        $re = Reply::where("name", $name)->find();
        if ($re) {
            return "数据已存在";
        }
        $arr = ["name" => $name, "staff_duty" => $dutyId, "staff_no" => "", "create_staff_no" => $no];
        $rec = Reply::create($arr);
        if (!$rec) {
            return "添加失败";
        }
        return "";
    }

    /**
     * @param $id
     * @param $name
     * @return string
     */
    public static function up($id, $name): string
    {
        $re = Reply::where("id", "<>", $id)->where("name", $name)->find();
        if ($re) {
            return "分类已存在~";
        }
        $rec = Reply::where("id", $id)->data(["name" => $name])->update();
        if (!$rec) {
            return "分类修改失败";
        }
        return "";
    }

    /**
     * @param $id
     * @return bool|string
     * @throws \Exception
     */
    public static function del($id): string
    {
        if (empty($id)) {
            return "数组不能为空";

        }
        $re = Reply::where("id", "in", $id)->select();
        if (!$re) {
            return "数据不存在~";
        }
        foreach ($re as $k => $v) {
            $inf = ReplyInfo::where("reply_id", $v["id"])->find();
            if ($inf) {
                return "有回复消息不能删除";
            }
        }
        $de = Reply::where("id", "in", $id)->delete();
        if (!$de) {
            return "删除失败";
        }
        return "";
    }

    /**
     * @param $page
     * @param $limit
     * @return array
     */
    public static function li($page, $limit)
    {
        $reSql = Reply::alias("r")
            ->leftjoin("ic_reply_info ri", "r.id = ri.reply_id")
            ->field("r.id,r.name,count(ri.id) as num")
            ->group("r.id");
        $duSql = Duty::getQueryByDataPermId($reSql, "r.create_staff_no");
        $re = $duSql->page($page, $limit)
            ->select();
        $reC = Reply::count();
        return listDate($re, $reC);
    }

    /**
     * @param $dutyIdArr
     * @param $staffNo
     * @return array
     * 获取回复内容
     */
    public static function treeList($dutyIdArr, $staffNo): array
    {
        // 表题
        $arTi = Reply::field("name,0 as reply_id,id,0 as auto")
            ->where("staff_duty", "in", $dutyIdArr)->all()->toArray();
        // 管理员数据
        $arIn = ReplyInfo::field("info as name,if(reply_id = 0,-1,reply_id) as reply_id,id,0 as auto")
            ->where("staff_duty", "in", $dutyIdArr)
            ->where("staff_no", "=", "")->all()->toArray();
        // 自己数据
        $arrInMY = ReplyInfo::field("info as name,if(reply_id = 0,-1,reply_id) as reply_id,id,auto")
            ->where("staff_duty", "in", $dutyIdArr)
            ->where("staff_no", "=", $staffNo)->order("id")->all()->toArray();

        $arrMy = [["name" => "我的", "reply_id" => 0, "id" => -1]];
        $da = array_merge($arrMy, $arTi, $arIn, $arrInMY);
        $data = [];

        if (count($da) > 1) {
            $data = getMenu($da, "reply_id", 0);
        } else {
            $data = $arrMy[0]["children"] = [];
        }

        return $data;
    }

    /**
     * @param $dutyIdArr
     * @param $staffNo
     * @return array
     */
    public static function getInfoList($dutyIdArr, $staffNo): array
    {
        // 管理员数据
        return ReplyInfo::field("info as name,if(reply_id = 0,-1,reply_id) as reply_id,id")
            ->where("staff_duty", "in", $dutyIdArr)
            ->where("staff_no", "=", "")->all()->toArray();

    }

    /**
     * @param $dutyIdArr
     * @param $staffNo
     * @return array
     */
    public static function getSelfInfoList($dutyIdArr, $staffNo): array
    {
        // 自己数据
        return ReplyInfo::field("info as name,if(reply_id = 0,-1,reply_id) as reply_id,id")
            ->where("staff_duty", "in", $dutyIdArr)
            ->where("staff_no", "=", $staffNo)->all()->toArray();
    }

    /**
     * @param $info
     * @param $staffNo
     * @return string
     */
    public static function addReplyIn($info, $staffNo, $dutyId): string
    {
        $arr = [
            "info" => $info, "staff_no" => $staffNo, "create_staff_no" => $staffNo,
            "name" => "我的", "staff_duty" => $dutyId
        ];
        $res = ReplyInfo::create($arr);
        if (!$res) return "失败";
        return "";
    }

    /**
     * @param $id
     * @param $info
     * @param $staffNo
     * @return string
     */
    public static function upReplyIn($id, $info, $staffNo): string
    {
        $arr = [
            "info" => $info
        ];
        $res = ReplyInfo::where("id", $id)->where("staff_no", $staffNo)->data($arr)->update();
        if (!$res) return "他人数据不能修改~";
        return "";
    }

    /**
     * @param $id
     * @param $staffNo
     * @return string
     */
    public static function delReplyIn($id, $staffNo): string
    {
        $res = ReplyInfo::where("id", $id)->where("staff_no", $staffNo)->find();
        if (!$res) {
            return "数据不存在";
        }
        ReplyInfo::where("id", $id)->delete();
        return "";
    }

    /**
     * @param $id
     * @param $staffNo
     * @param $auto
     * @return string
     * @throws \Exception
     */
    public static function autoReplyIn($id, $staffNo,$auto): string
    {
        $res = ReplyInfo::where("id", $id)->where("staff_no", $staffNo)->where("auto",$auto)->find();
        if ($res) {
            return "状态已修改";
        }
        ReplyInfo::where("id", $id)->data(["auto"=>$auto])->update();
        return "";
    }

    /**
     * 列表 数据 第一次聊天都在这里记录
     */
    const oneNewChatSet = "ic_new_chat_auto";
    /**
     * 自动回复次数
     */
    const _count = "_count";
    /**
     * 客服回复内容
     */
    const ic_reply_ = "ic_reply_";

    /**
     * 自动回复内容
     */
    public static function autoReplayInfo(): string
    {
        $infoNum = 1;
        $redis = Cache::store('default')->handler();
        $oneNewChatSet = self::oneNewChatSet;
        $newChatCou = $redis->lLen($oneNewChatSet);
        // 回复消息
        $replyEnd = "";
        for ($i = $newChatCou; $i > 0; $i--) {

            // 获取是否第一次聊天
            $UserNoAndStaffNo = $redis->lPop($oneNewChatSet);

            // 现在第几次聊天
            $oneNewChatSetCount = $UserNoAndStaffNo . self::_count;
            $userNo = $redis->hGet($oneNewChatSetCount, 1);
            $staffNo = $redis->hGet($oneNewChatSetCount, 2);

            $num = $redis->hGet($oneNewChatSetCount, 3);


            $set = self::ic_reply_;
            // 获取我的回复消息
            $replyInfo = $redis->hGet($set . $staffNo, $infoNum);
            if (!$replyInfo) {
                self::setNewInfo($redis, $staffNo, $infoNum);
            }

            $set = self::ic_reply_;
            // 下一次聊天准备
            $replyEnd = $redis->hGet($set . $staffNo, $num);
            if ($replyEnd) {
                // 间隔时间到执行
                $replyEndTime = $redis->hGet($oneNewChatSetCount, 4);
                if (time() >= $replyEndTime) {
                    $staffData = Staff::field("is_reply_auto,reply_auto_time")->where("staff_no", $staffNo)->find();
                    if (!$staffData) {
                        Log::info("autoReplayInfo:客服不存在~");
                        continue;
                    }
                    $redis->hSet($oneNewChatSetCount, 3, $num + 1);
                    $redis->hSet($oneNewChatSetCount, 4, time() + $staffData["reply_auto_time"]);
                    Log::info("autoReplayInfo_下一次聊天_符合:{$replyEndTime}:time()");
                } else {
                    // 间隔时间未到不执行 返回信息空
                    $replyEnd = "";
                }
                // 房间号
                $redis->rPush($oneNewChatSet, $UserNoAndStaffNo);
                Log::info("autoReplayInfo_下一次聊天_推入:$UserNoAndStaffNo");
            } else {
                $redis->del($oneNewChatSetCount);
                Log::info("autoReplayInfo_下一次聊天_删除:$UserNoAndStaffNo");
            }

            if ($replyEnd) {
                // 日志写入
                $staffInfo = Staff::where("staff_no", $staffNo)->find();
                $userInfo = \app\admin\model\User::where("no", $userNo)->find();
                $isMen = \app\admin\model\User::getIsMen($userInfo["mobile"]);
                $res = Chat::TimerToUser($userInfo["id"], $staffInfo["id"], $replyEnd, $isMen);
                if ($res) {
                    Log::info("autoReplayInfo_err:{$res}");
                }
            }
            Log::info("autoReplayInfo:" . $UserNoAndStaffNo . "-" . $replyEnd);
        }
        return "";
    }

    /**
     * 聊天第一次触发
     * @param $userNo
     * @param $staffNo
     * @return string
     */
    public static function touchOffAutoReply($userNo, $staffNo): string
    {
        $staffData = Staff::field("is_reply_auto,reply_auto_time")->where("staff_no", $staffNo)->find();
        if (!$staffData) {
            Log::info("touchOffAutoReply:客服不存在~");
            return "";
        }


        // 添加队列
        if ($staffData["is_reply_auto"] == 1) {
            $redis = Cache::store('default')->handler();
            $oneNewChatSet = self::oneNewChatSet;
            // 队列
            $UserNoAndStaffNo = $userNo . "_" . $staffNo;

            // hash
            $oneNewChatSetCount = $UserNoAndStaffNo . self::_count;

            $cg = $redis->hGet($oneNewChatSetCount, 1);
            if (!$cg) {
                $redis->rPush($oneNewChatSet, $UserNoAndStaffNo);
            }
            $redis->hSet($oneNewChatSetCount, 1, $userNo);
            $redis->hSet($oneNewChatSetCount, 2, $staffNo);
            $redis->hSet($oneNewChatSetCount, 3, 1);
            $redis->hSet($oneNewChatSetCount, 4, time() + $staffData["reply_auto_time"]);
            Log::info("touchOffAutoReply:" . $UserNoAndStaffNo);
        }

        return "";
    }

    /**
     * 触发删除
     * @param $userNo
     * @param $staffNo
     */
    public static function touchOffAutoReplyDelete($userNo, $staffNo)
    {
        $redis = Cache::store('default')->handler();

        // 删除队列
        $oneNewChatSet = self::oneNewChatSet;
        $UserNoAndStaffNo = $userNo . "_" . $staffNo;
        $redis->lRem($oneNewChatSet, $UserNoAndStaffNo);

        // 删除hash
        $oneNewChatSetCount = $UserNoAndStaffNo . self::_count;
        $redis->hDel($oneNewChatSetCount, 1);
        $redis->hDel($oneNewChatSetCount, 2);
        $redis->hDel($oneNewChatSetCount, 3);
        $redis->hDel($oneNewChatSetCount, 4);

        Log::info("touchOffAutoReplyDelete:" . $UserNoAndStaffNo);
    }

    /**
     * 获取最新信息
     * @param $redis
     * @param $staffNo
     * @param $infoNum
     */
    public static function setNewInfo($redis, $staffNo, $infoNum=1)
    {
        // 获取我的回复消息
        $set = self::ic_reply_;
        $data = ReplyInfo::where("staff_no", $staffNo)->where("create_staff_no", $staffNo)->where("auto",1)->order("id")->column("info");
        $redis->del($set . $staffNo);
        foreach ($data as $k => $v) {
            $redis->hSet($set . $staffNo, $k + 1, $v);
        }

    }

}